import { LoginUserMenuItem, getLoginUserMenuList } from "@/api";
import { ButtonRouteMeta } from "./routeinfo";
import { RouteRecordRaw, Router } from "vue-router";
import { RouteTool, getModule } from "./tools";

const envObj = import.meta.env
type DynamicRouter = (application: string | LoginUserMenuItem[], routerInstance: Router) => Promise<{
  buttons: ButtonRouteMeta[],
  originalMenuList: LoginUserMenuItem[],
  formattedRoute: RouteRecordRaw[]
}>
/**
 * 将传入的vue-router实例写入动态路由
 * @param {string|Array} application 要切换的应用code
 * @param {Router} routerInstance  vue-router实例对象
 */
const setupDynamicRouter: DynamicRouter = async (application: string | LoginUserMenuItem[], routerInstance: Router,) => {
  if (envObj.DEV) console.log(Date.now(), '获取路由记录中');
  const menulist = Array.isArray(application)
    ? application
    : await getLoginUserMenuList({ application }).then(({ data }) => data.data);
  if (envObj.DEV) console.log(Date.now(), '已获得路由配置');
  sessionStorage.setItem('menu', JSON.stringify(menulist));
  const routeUtil = new RouteTool(MenuRouterFormat(menulist))
  const formattedRoute = routeUtil.getRouteConfig()
  if (envObj.DEV) console.log(Date.now(), '格式化路由完成');
  authentication.children = defaultMainChildren.concat(formattedRoute);
  // authentication.redirect = formattedRoute[0]
  routerInstance.addRoute(authentication);
  if (envObj.DEV) console.log(Date.now(), '动态路由装配成功');
  return {
    buttons: routeUtil.buttons,
    originalMenuList: menulist,
    formattedRoute,
  };
}


function MenuRouterFormat(list: LoginUserMenuItem[], parentPath = '/'): LoginUserMenuItem[] {
  return list.map(i => {
    const router = (i.router || '').replace(/\/$/, '')
    i.router = router
    if (!router.startsWith('/')) {
      i.router = parentPath + router
    }
    if (Array.isArray(i.children)) {
      // 如果有子菜单,必须后缀加一个/以方便更深度的菜单有个兜底父级
      i.children = MenuRouterFormat(i.children, i.router + '/')
    }
    return i
  })
}

const publicRoutes: RouteRecordRaw[] = [
  {
    name: "login",
    path: "/login",
    component: getModule('/system/login'),
  },
  {
    path: "/pagenotfound",
    name: "notFount",
    meta: {
      title: "页面未找到",
    },
    component: getModule('/system/errorPage/404'),
  },
];
const defaultMainChildren: RouteRecordRaw[] = [
  // 请勿删除该配置项,动态路由加载后,该配置项会在登录时被覆盖

  {
    name: "401",
    path: "401",
    meta: {
      title: "无访问权限",
    },
    component: getModule('/system/errorPage/401'),
  },
  {
    path: "404",
    name: "404",
    meta: {
      title: "页面未找到",
    },
    component: getModule('/system/errorPage/404'),
  },
];
const authentication: RouteRecordRaw = {
  path: "/",
  name: "main",
  component: getModule('/layout/default-layout'),
  children: defaultMainChildren,
  meta: {
    configured: false,
  },
  beforeEnter() {
    // return true;
    // 如果访问页面时有token或访问的公共路径就放行
    if (sessionStorage.getItem("token")) {
      return true;
    }
    console.log(sessionStorage.getItem("token"));
    return { name: "login" };
  },
};
export { authentication, defaultMainChildren, setupDynamicRouter, MenuRouterFormat, publicRoutes };